package org.pku_uestc.hackathon.utils;

import java.util.ArrayList;
import java.util.List;

import org.pku_uestc.hackathon.bean.ContactInfo;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;

public class ContactUtils {

	private static final String[] PHONES_PROJECTION = new String[] {
			Phone.DISPLAY_NAME, Phone.NUMBER /* , Photo.PHOTO_ID,Phone.CONTACT_ID */};

	/** 联系人显示名称 **/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;

	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;

	/** 得到手机通讯录联系人信息 **/
	public static List<ContactInfo> getPhoneContacts(Context context) {
		List<ContactInfo> contactInfoList = new ArrayList<ContactInfo>();
		ContactInfo info;
		ContentResolver resolver = context.getContentResolver();
		// 获取手机联系人
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);

		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {

				// 得到手机号码
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				// 当手机号码为空的或者为空字段 跳过当前循环
				if (TextUtils.isEmpty(phoneNumber))
					continue;

				// 得到联系人名称
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);
				info = new ContactInfo();
				info.setName(contactName);
				info.setNumber(phoneNumber);
				contactInfoList.add(info);
			}
			phoneCursor.close();
		}
		return ContactComparator.sort(contactInfoList);
	}

}
